<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇古文记忆游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f4f4f9;
        }

        h1 {
            margin: 20px 0;
            font-size: 36px;
        }

        canvas {
            border: 2px solid #000;
            background-color: #222;
            display: block;
            margin: 20px auto;
        }

        .score {
            font-size: 24px;
        }

        .sentence {
            font-size: 20px;
            color: red;
            margin-top: 20px;
        }

        .feedback {
            font-size: 20px;
            color: rgb(125, 51, 243);
            margin-top: 20px;
        }

        .bottom-text {
            color: black;
            font-size: 16px;
            margin-top: 20px;
            background-color: white;
            padding: 5px;
            border-radius: 5px;
        }

        .hidden {
            display: none;
        }

        #muteBtn {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            font-size: 24px;
            cursor: pointer;
            background: none;
            border: 2px solid #333;
            border-radius: 5px;
        }

        #readyBtn {
            display: block;
            width: 200px;  /* 固定宽度 */
            height: 50px;  /* 固定高度 */
            margin: 20px auto;
            padding: 10px 20px;
            font-size: 18px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            /* 确保按钮内容垂直居中 */
            line-height: 30px;
            text-align: center;
        }

        #readyBtn:hover {
            background-color: #45a049;
            transform: scale(1.05);
        }

        /* 学习界面样式 */
        #studySection {
            text-align: center;
            margin: 20px auto;
            padding: 20px;
        }

        #studyText {
            margin-bottom: 20px;
            font-size: 24px;
        }

        #studyInstruction {
            margin-bottom: 20px;
            font-size: 18px;
            color: #666;
        }

        /* 游戏失败弹出巨大的emoji提示 */
        #gameOverEmoji {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        /* 当移除 hidden 类时显示 */
        #gameOverEmoji.show {
            display: flex;
        }

        #gameOverEmoji .emoji {
            font-size: 120px;
        }

        /* 修改模式选择按钮样式 */
        .mode-select {
            margin: 20px auto;
            text-align: center;
            display: none; /* 游戏开始后隐藏 */
        }

        .mode-btn {
            padding: 10px 20px;
            margin: 0 10px;
            font-size: 18px;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            transition: all 0.3s ease;
            background: #f0f0f0;
            color: #666;
        }

        .mode-btn.active {
            background: #4CAF50;
            color: white;
        }

        /* 修改分数显示样式 */
        .score-container {
            position: fixed;
            top: 10px;
            left: 0;
            right: 0;
            text-align: center;
            z-index: 100;
            pointer-events: none; /* 防止干扰游戏操作 */
        }

        .score {
            display: inline-block;
            margin: 0 20px;
            padding: 5px 15px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            border-radius: 20px;
            font-size: 18px;
        }

        /* 游戏画布容器 */
        .game-container {
            position: relative;
            width: 800px;
            height: 600px;
            margin: 0 auto;
            overflow: hidden; /* 防止页面滚动 */
        }

        /* 添加倒计时样式 */
        .countdown {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 120px;
            color: #4CAF50;
            text-shadow: 0 0 10px rgba(0,0,0,0.3);
            z-index: 1000;
            font-weight: bold;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .countdown.show {
            opacity: 1;
        }

        .get-ready {
            position: fixed;
            top: 40%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 36px;
            color: #2196F3;
            text-shadow: 0 0 10px rgba(0,0,0,0.2);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .get-ready.show {
            opacity: 1;
        }

        /* 添加句子卡选择样式 */
        .sentence-cards {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.2);
            max-width: 80%;
            max-height: 80vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .sentence-card {
            margin: 10px 0;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .sentence-card:hover {
            border-color: #4CAF50;
            background: #f5f5f5;
        }

        .sentence-card.selected {
            border-color: #4CAF50;
            background: #E8F5E9;
        }

        .select-sentence-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            z-index: 100;
        }

        .select-sentence-btn:hover {
            background: #45a049;
        }
    </style>
</head>
<body>

<h1>贪吃蛇古文记忆游戏</h1>
<div class="mode-select">
    <button class="mode-btn" onclick="switchMode()">切换为双人模式</button>
</div>
<div id="studySection">
    <h2 id="studyText"></h2>
    <p id="studyInstruction">请先记忆上面的句子</p>
    <button id="readyBtn" onclick="startGameAfterStudy()">我已经记住了</button>
    <p>创作人: 阮博凯</p>
</div>
<div class="game-container">
    <div class="score-container">
        <div class="score" id="score">玩家1得分: 0</div>
        <div class="score" id="score2">玩家2得分: 0</div>
    </div>
    <canvas id="gameCanvas" width="800" height="600"></canvas>
</div>
<p style="display: none;" class="sentence">目标：<span id="currentSentence">准备好开始游戏！</span></p>
<p class="feedback" id="feedback"></p>
<p class="bottom-text" id="bottom-text">底部提示文字</p>
<button id="startBtn" onclick="startGame()">开始游戏</button>

<!-- 新增游戏失败时弹出的巨大😭 emoji -->
<div id="gameOverEmoji" class="hidden">
    <span class="emoji">😭</span>
</div>

<!-- 添加音频元素 -->
<audio id="bgMusic" loop>
    <source src="background-music.mp3" type="audio/mp3">
</audio>
<audio id="eatSound">
    <source src="eat-sound.mp3" type="audio/mp3">
</audio>
<audio id="gameOverSound">
    <source src="game-over.mp3" type="audio/mp3">
</audio>
<button id="muteBtn" onclick="toggleMute()">🔊</button>

<!-- 添加倒计时元素到HTML -->
<div class="countdown"></div>
<div class="get-ready">准备开始！</div>

<!-- 添加HTML元素 -->
<button class="select-sentence-btn" onclick="showSentenceCards()">选择句子</button>
<div class="sentence-cards">
    <h2 style="text-align: center; margin-bottom: 20px;">选择学习句子</h2>
    <div id="sentenceList"></div>
</div>

<script>
    const canvas = document.getElementById("gameCanvas");
    const ctx = canvas.getContext("2d");

    const snakeSize = 20;
    let snake = [{ x: 100, y: 100 }];
    let snake2 = [{ x: canvas.width - 100, y: canvas.height - 100 }];
    let direction = "RIGHT";
    let direction2 = "LEFT";
    let food = [];
    let score = 0;
    let score2 = 0;
    let gameInterval;
    let isGameStarted = false;
    let gameSpeed = 200;
    let isMuted = false;

    // 添加句子相关变量
    const sentences = [
        "古之欲明明德于天下者，先治其国；欲治其国者，先齐其家；欲齐其家者，先修其身；欲修其身者，先正其心；欲正其心者，先诚其意；欲诚其意者，先致其知；致知在格物。",
        "物格而后知至；知至而后意诚；意诚而后心正；心正而后身修；身修而后家齐；家齐而后国治；国治而后天下平。"

    ];
    
    let currentSentenceIndex = 0;
    let currentSentence = [];
    let targetWordIndex = 0;
    let targetWordIndex2 = 0;
    let collectedTexts = [];
    let collectedTexts2 = [];
    let correctWord = '';
    let correctWord2 = '';

    // 添加游戏模式变量
    let isDoubleMode = false;

    // 添加速度相关变量
    const DEFAULT_SPEED = 200;  // 默认速度（数值越大越慢）
    const FAST_SPEED = 100;     // 快速移动速度
    const SPEED_DECAY = 10;     // 每帧减速量
    let currentSpeed = DEFAULT_SPEED;
    let lastKeyPressTime = 0;
    const KEY_PRESS_THRESHOLD = 200; // 判定为快速按键的时间阈值（毫秒）

    // 添加玩家状态变量
    let player1Dead = false;
    let player2Dead = false;

    // 添加生命值变量
    let lives1 = 3;
    let lives2 = 3;

    // 添加倒计时元素到HTML
    document.body.insertAdjacentHTML('beforeend', `
        <div class="countdown"></div>
        <div class="get-ready">准备开始！</div>
    `);

    // 添加音频相关变量和函数
    let bgMusic = document.getElementById("bgMusic");

    function startGame() {
        // 重置生命值
        lives1 = 3;
        lives2 = 3;
        
        // 重置玩家状态
        player1Dead = false;
        player2Dead = false;
        
        score = 0;
        if (isDoubleMode) {
            score2 = 0;
        }
        
        // 处理当前句子
        let cleanSentence = removePunctuation(sentences[currentSentenceIndex]);
        currentSentence = cleanSentence.split('');
        console.log("Starting game with sentence:", currentSentence);
        
        // 初始化两个玩家的目标字
        targetWordIndex = 0;
        targetWordIndex2 = 0;
        correctWord = currentSentence[targetWordIndex];
        correctWord2 = currentSentence[targetWordIndex2];
        
        console.log("Initial correct words:", correctWord, correctWord2);
        
        // 清空收集的文字
        collectedTexts = [];
        collectedTexts2 = [];
        
        // 更新分数显示
        updateScoreDisplay();
        
        // 隐藏开始按钮
        document.getElementById("startBtn").classList.add("hidden");
        
        // 初始化蛇的位置
        snake = [{ x: 100, y: 100 }];
        if (isDoubleMode) {
            snake2 = [{ x: canvas.width - 100, y: canvas.height - 100 }];
            direction2 = "LEFT";
        }
        direction = "RIGHT";
        
        // 设置游戏状态为开始
        isGameStarted = true;
        
        // 生成初始食物
        food = [];
        spawnFood();
        
        // 重置速度相关变量
        currentSpeed = DEFAULT_SPEED;
        lastKeyPressTime = 0;
        
        // 启动游戏循环
        if (gameInterval) clearInterval(gameInterval);
        gameInterval = setInterval(gameLoop, currentSpeed);
        
        // 添加键盘监听
        document.addEventListener("keydown", changeDirection);
    }

    function spawnFood() {
        // 如果是双人模式且已有食物，检查是否存在正确的食物
        if (isDoubleMode && food.length > 0 && (player1Dead || player2Dead)) {
            // 检查当前食物中是否包含两个玩家需要的正确文字
            const hasCorrectFood1 = food.some(f => f.word === correctWord);
            const hasCorrectFood2 = food.some(f => f.word === correctWord2);
            
            // 如果缺少任何一个正确的食物，重新生成所有食物
            if (!hasCorrectFood1 || !hasCorrectFood2) {
                generateNewFood();
            }
            return;
        }

        generateNewFood();
    }

    function generateNewFood() {
        food = [];
        
        // 获取当前两个玩家的目标文字
        const target1 = correctWord;
        const target2 = correctWord2;
        
        // 如果两个玩家的目标文字相同，只生成一个食物
        if (target1 === target2) {
            const pos = getValidPosition();
            food.push({
                x: pos.x,
                y: pos.y,
                word: target1,
                isCorrect: true
            });
        } else {
            // 生成玩家1的食物
            const pos1 = getValidPosition();
            food.push({
                x: pos1.x,
                y: pos1.y,
                word: target1,
                isCorrect: true
            });
            
            // 生成玩家2的食物（如果是双人模式且玩家2活着）
            if (isDoubleMode && !player2Dead) {
                const pos2 = getValidPosition();
                food.push({
                    x: pos2.x,
                    y: pos2.y,
                    word: target2,
                    isCorrect: true
                });
            }
        }
        
        // 添加错误食物
        const maxExtraFood = isDoubleMode ? 5 : 3;
        let wrongWords = currentSentence.filter(c => 
            c !== target1 && 
            c !== target2 && 
            c.trim() !== ""
        );
        
        for (let i = 0; i < maxExtraFood && wrongWords.length > 0; i++) {
            const pos = getValidPosition();
            const randomIndex = Math.floor(Math.random() * wrongWords.length);
            const word = wrongWords[randomIndex];
            wrongWords.splice(randomIndex, 1);
            
            food.push({
                x: pos.x,
                y: pos.y,
                word: word,
                isCorrect: false
            });
        }
    }

    function removePunctuation(str) {
        return str.replace(/[，。？：！、；]/g, '');
    }

    function gameLoop() {
        if (!isGameStarted) return;

        // 处理速度衰减
        if (currentSpeed < DEFAULT_SPEED) {
            currentSpeed = Math.min(DEFAULT_SPEED, currentSpeed + SPEED_DECAY);
            clearInterval(gameInterval);
            gameInterval = setInterval(gameLoop, currentSpeed);
        }

        // 更新画面
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 绘制活着的蛇
        if (!player1Dead) {
            // 移动和绘制蛇1
            let head = { ...snake[0] };
            if (direction === "UP") head.y -= snakeSize;
            if (direction === "DOWN") head.y += snakeSize;
            if (direction === "LEFT") head.x -= snakeSize;
            if (direction === "RIGHT") head.x += snakeSize;

            // 检查碰撞并处理穿墙
            checkCollision(head);
            
            // 检查与蛇2的碰撞
            if (isDoubleMode && !player2Dead && checkSnakeCollision(head, snake2)) {
                handlePlayerDeath(1);
            } else {
                snake.unshift(head);
                let ateFood = handleFoodCollisionForPlayer(1, head);
                if (!ateFood) snake.pop();
                drawSnake();
            }
        }

        if (isDoubleMode && !player2Dead) {
            // 移动和绘制蛇2
            let head2 = { ...snake2[0] };
            if (direction2 === "UP") head2.y -= snakeSize;
            if (direction2 === "DOWN") head2.y += snakeSize;
            if (direction2 === "LEFT") head2.x -= snakeSize;
            if (direction2 === "RIGHT") head2.x += snakeSize;

            // 检查碰撞并处理穿墙
            checkCollision(head2);
            
            // 检查与蛇1的碰撞
            if (!player1Dead && checkSnakeCollision(head2, snake)) {
                handlePlayerDeath(2);
            } else {
                snake2.unshift(head2);
                let ateFood = handleFoodCollisionForPlayer(2, head2);
                if (!ateFood) snake2.pop();
                drawSnake2();
            }
        }

        // 绘制食物
        drawFood();
    }

    function checkCollision(head) {
        // 穿墙处理
        if (head.x < 0) {
            head.x = canvas.width - snakeSize;
        } else if (head.x >= canvas.width) {
            head.x = 0;
        }
        
        if (head.y < 0) {
            head.y = canvas.height - snakeSize;
        } else if (head.y >= canvas.height) {
            head.y = 0;
        }
        
        return false; // 不再检测墙体碰撞
    }

    function checkSnakeCollision(head, otherSnake) {
        return otherSnake.some(segment => 
            segment.x === head.x && segment.y === head.y);
    }

    function handleFoodCollisionForPlayer(playerNum, head) {
        let ateFood = false;
        food.forEach((item, index) => {
            if (head.x === item.x && head.y === item.y) {
                const currentCorrectWord = playerNum === 1 ? correctWord : correctWord2;
                if (item.word === currentCorrectWord) {
                    ateFood = true;
                    
                    // 播放吃食物音效
                    const eatSound = document.getElementById("eatSound");
                    if (!isMuted && eatSound) {
                        eatSound.volume = 0.5; // 设置音量为50%
                        eatSound.currentTime = 0; // 重置音频时间
                        eatSound.play().catch(error => {
                            console.log("吃食物音效播放失败:", error);
                        });
                    }
                    
                    if (playerNum === 1) {
                        score += 10;
                        collectedTexts.push(correctWord);
                        targetWordIndex++;
                        correctWord = currentSentence[targetWordIndex];
                        document.getElementById("score").textContent = `玩家1得分: ${score} (❤️: ${lives1})`;
                    } else {
                        score2 += 10;
                        collectedTexts2.push(correctWord2);
                        targetWordIndex2++;
                        correctWord2 = currentSentence[targetWordIndex2];
                        document.getElementById("score2").textContent = `玩家2得分: ${score2} (❤️: ${lives2})`;
                    }
                    
                    // 确保场上有正确的食物
                    spawnFood();
                } else {
                    handlePlayerDeath(playerNum);
                }
            }
        });
        return ateFood;
    }

    function getValidPosition() {
        let pos;
        let attempts = 0;
        const maxAttempts = 100;  // 防止无限循环
        
        do {
            pos = {
                x: Math.floor(Math.random() * ((canvas.width - snakeSize) / snakeSize)) * snakeSize,
                y: Math.floor(Math.random() * ((canvas.height - snakeSize) / snakeSize)) * snakeSize
            };
            attempts++;
            
            // 如果尝试次数过多，重置食物位置的查找
            if (attempts > maxAttempts) {
                console.log("重置食物位置查找");
                return {
                    x: Math.floor(Math.random() * ((canvas.width - snakeSize) / snakeSize)) * snakeSize,
                    y: Math.floor(Math.random() * ((canvas.height - snakeSize) / snakeSize)) * snakeSize
                };
            }
        } while (
            // 检查是否与蛇1重叠或在蛇1头部一步之内
            isNearSnakeHead(pos, snake[0], direction) ||
            snake.some(segment => segment.x === pos.x && segment.y === pos.y) ||
            // 检查是否与蛇2重叠或在蛇2头部一步之内
            (isDoubleMode && !player2Dead && (
                isNearSnakeHead(pos, snake2[0], direction2) ||
                snake2.some(segment => segment.x === pos.x && segment.y === pos.y)
            )) ||
            // 检查是否与其他食物重叠
            food.some(item => item.x === pos.x && item.y === pos.y)
        );
        
        return pos;
    }

    // 添加检查是否在蛇头附近的函数
    function isNearSnakeHead(pos, head, snakeDirection) {
        if (!head) return false;

        // 获取蛇头下一步可能的位置
        const nextPositions = {
            "UP": { x: head.x, y: head.y - snakeSize },
            "DOWN": { x: head.x, y: head.y + snakeSize },
            "LEFT": { x: head.x - snakeSize, y: head.y },
            "RIGHT": { x: head.x + snakeSize, y: head.y }
        };

        // 处理穿墙情况
        Object.values(nextPositions).forEach(nextPos => {
            if (nextPos.x < 0) nextPos.x = canvas.width - snakeSize;
            if (nextPos.x >= canvas.width) nextPos.x = 0;
            if (nextPos.y < 0) nextPos.y = canvas.height - snakeSize;
            if (nextPos.y >= canvas.height) nextPos.y = 0;
        });

        // 检查是否在蛇头当前位置或下一步可能的位置
        return (pos.x === head.x && pos.y === head.y) || 
               Object.values(nextPositions).some(nextPos => 
                   pos.x === nextPos.x && pos.y === nextPos.y
               );
    }

    function drawSnake() {
        // 绘制蛇身
        snake.forEach((segment, index) => {
            const isHead = index === 0;
            
            // 创建蛇身渐变色
            const gradient = ctx.createLinearGradient(
                segment.x, segment.y, 
                segment.x + snakeSize, segment.y + snakeSize
            );
            
            if (isHead) {
                // 蛇头使用特殊的颜色
                gradient.addColorStop(0, '#4CAF50');
                gradient.addColorStop(1, '#45a049');
                
                // 保存当前状态
                ctx.save();
                
                // 绘制圆形蛇头
                ctx.beginPath();
                ctx.fillStyle = gradient;
                ctx.arc(
                    segment.x + snakeSize/2,
                    segment.y + snakeSize/2,
                    snakeSize/2,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
                
                // 添加眼睛
                ctx.fillStyle = 'white';
                let eyeX1, eyeX2, eyeY;
                
                // 根据方向调整眼睛位置
                switch(direction) {
                    case 'RIGHT':
                        eyeX1 = segment.x + snakeSize - 6;
                        eyeX2 = eyeX1;
                        eyeY1 = segment.y + 6;
                        eyeY2 = segment.y + snakeSize - 6;
                        break;
                    case 'LEFT':
                        eyeX1 = segment.x + 6;
                        eyeX2 = eyeX1;
                        eyeY1 = segment.y + 6;
                        eyeY2 = segment.y + snakeSize - 6;
                        break;
                    case 'UP':
                        eyeX1 = segment.x + 6;
                        eyeX2 = segment.x + snakeSize - 6;
                        eyeY1 = segment.y + 6;
                        eyeY2 = eyeY1;
                        break;
                    case 'DOWN':
                        eyeX1 = segment.x + 6;
                        eyeX2 = segment.x + snakeSize - 6;
                        eyeY1 = segment.y + snakeSize - 6;
                        eyeY2 = eyeY1;
                        break;
                }
                
                // 绘制眼睛
                ctx.beginPath();
                ctx.arc(eyeX1, eyeY1, 2, 0, Math.PI * 2);
                ctx.arc(eyeX2, eyeY2, 2, 0, Math.PI * 2);
                ctx.fillStyle = 'black';
                ctx.fill();
                
                ctx.restore();
            } else {
                // 蛇身使用渐变色
                gradient.addColorStop(0, `hsl(${120 + index * 5}, 70%, 50%)`);
                gradient.addColorStop(1, `hsl(${120 + index * 5}, 70%, 45%)`);
                
                // 绘制圆角矩形作为蛇身
                ctx.beginPath();
                ctx.fillStyle = gradient;
                roundRect(
                    ctx,
                    segment.x,
                    segment.y,
                    snakeSize,
                    snakeSize,
                    5
                );
                ctx.fill();
                
                // 从第二个身体段开始显示文字（尾部开始）
                if (index > 0) {
                    const textIndex = index - 1;
                    if (textIndex < collectedTexts.length) {
                        ctx.fillStyle = "white";
                        ctx.font = "16px Arial";
                        ctx.textAlign = "center";
                        ctx.textBaseline = "middle";
                        ctx.fillText(
                            collectedTexts[textIndex],
                            segment.x + snakeSize/2,
                            segment.y + snakeSize/2
                        );
                    }
                }
            }
        });
    }

    function drawSnake2() {
        snake2.forEach((segment, index) => {
            const isHead = index === 0;
            
            const gradient = ctx.createLinearGradient(
                segment.x, segment.y, 
                segment.x + snakeSize, segment.y + snakeSize
            );
            
            if (isHead) {
                gradient.addColorStop(0, '#FF4081');  // 粉色蛇头
                gradient.addColorStop(1, '#F50057');
                
                ctx.save();
                ctx.beginPath();
                ctx.fillStyle = gradient;
                ctx.arc(
                    segment.x + snakeSize/2,
                    segment.y + snakeSize/2,
                    snakeSize/2,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
                
                // 绘制眼睛
                drawEyes(segment, direction2);
                
                ctx.restore();
            } else {
                gradient.addColorStop(0, `hsl(${340 + index * 5}, 70%, 50%)`);
                gradient.addColorStop(1, `hsl(${340 + index * 5}, 70%, 45%)`);
                
                ctx.beginPath();
                ctx.fillStyle = gradient;
                roundRect(
                    ctx,
                    segment.x,
                    segment.y,
                    snakeSize,
                    snakeSize,
                    5
                );
                ctx.fill();
                
                if (index > 0) {
                    const textIndex = index - 1;
                    if (textIndex < collectedTexts2.length) {
                        ctx.fillStyle = "white";
                        ctx.font = "16px Arial";
                        ctx.textAlign = "center";
                        ctx.textBaseline = "middle";
                        ctx.fillText(
                            collectedTexts2[textIndex],
                            segment.x + snakeSize/2,
                            segment.y + snakeSize/2
                        );
                    }
                }
            }
        });
    }

    // 添加圆角矩形绘制函数
    function roundRect(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
    }

    // 修改食物绘制函数，使其更美观
    function drawFood() {
        if (!food || food.length === 0) return;
        
        food.forEach(item => {
            // 绘制圆形食物，统一使用蓝色
            ctx.beginPath();
            ctx.fillStyle = '#2196F3';  // 所有食物统一使用蓝色
            
            // 绘制圆形底色
            ctx.arc(
                item.x + snakeSize/2,
                item.y + snakeSize/2,
                snakeSize/2 - 2,
                0,
                Math.PI * 2
            );
            ctx.fill();
            
            // 绘制文字
            ctx.fillStyle = "white";
            ctx.font = "bold 16px Arial";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText(
                item.word,
                item.x + snakeSize/2,
                item.y + snakeSize/2
            );
        });
    }

    function changeDirection(event) {
        const key = event.key.toLowerCase();
        const currentTime = Date.now();
        
        // 处理方向键
        if (key === "arrowup" || key === "arrowdown" || 
            key === "arrowleft" || key === "arrowright" ||
            key === "w" || key === "s" || key === "a" || key === "d") {
            
            // 检测快速按键
            if (currentTime - lastKeyPressTime < KEY_PRESS_THRESHOLD) {
                // 加速
                currentSpeed = FAST_SPEED;
                
                // 重新设置游戏循环以更新速度
                if (gameInterval) {
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, currentSpeed);
                }
            }
            
            lastKeyPressTime = currentTime;
        }

        // 原有的方向控制逻辑
        if (key === "arrowup" && direction !== "DOWN") direction = "UP";
        if (key === "arrowdown" && direction !== "UP") direction = "DOWN";
        if (key === "arrowleft" && direction !== "RIGHT") direction = "LEFT";
        if (key === "arrowright" && direction !== "LEFT") direction = "RIGHT";

        // 玩家2的控制
        if (isDoubleMode) {
            if (key === "w" && direction2 !== "DOWN") direction2 = "UP";
            if (key === "s" && direction2 !== "UP") direction2 = "DOWN";
            if (key === "a" && direction2 !== "RIGHT") direction2 = "LEFT";
            if (key === "d" && direction2 !== "LEFT") direction2 = "RIGHT";
        }
    }

    // 游戏失败时显示巨大emoji，并在2秒后弹出预习界面
    function showGameOverEmoji() {
        const emojiOverlay = document.getElementById("gameOverEmoji");
        emojiOverlay.classList.add("show");
        setTimeout(() => {
            emojiOverlay.classList.remove("show");
            showStudySection();
        }, 2000);
    }

    function endGame() {
        isGameStarted = false;
        clearInterval(gameInterval);
        
        // 停止背景音乐
        if (bgMusic) {
            bgMusic.pause();
            bgMusic.currentTime = 0;
        }
        
        // 播放游戏结束音效
        const gameOverSound = document.getElementById("gameOverSound");
        if (!isMuted && gameOverSound) {
            gameOverSound.volume = 0.5;
            gameOverSound.currentTime = 0;
            gameOverSound.play().catch(error => {
                console.log("游戏结束音效播放失败:", error);
            });
        }
        
        if (!isDoubleMode || (player1Dead && player2Dead)) {
            // 显示游戏结束动画
            showGameOver();
            
            // 延迟后重新开始当前句子
            setTimeout(() => {
                resetGame();
                showStudySection();
            }, 2000);
        }
    }

    function toggleMute() {
        isMuted = !isMuted;
        const muteBtn = document.getElementById("muteBtn");
        
        if (isMuted) {
            muteBtn.textContent = "🔇";
            if (bgMusic) {
                bgMusic.pause();
            }
        } else {
            muteBtn.textContent = "🔊";
            if (bgMusic && isGameStarted) {
                bgMusic.play().catch(error => {
                    console.log("背景音乐播放失败:", error);
                });
            }
        }
    }

    // 添加学习界面到游戏界面的切换函数
    function startGameAfterStudy() {
        // 隐藏学习界面和模式选择
        document.getElementById("studySection").style.display = "none";
        document.querySelector('.mode-select').style.display = "none";
        
        // 显示游戏界面
        document.getElementById("gameCanvas").style.display = "block";
        document.getElementsByClassName("score-container")[0].style.display = "block";
        
        // 播放背景音乐
        if (!isMuted && bgMusic) {
            bgMusic.volume = 0.3; // 设置音量为30%
            bgMusic.play().catch(error => {
                console.log("背景音乐播放失败:", error);
            });
        }
        
        // 开始倒计时
        startCountdown();
    }

    function startCountdown() {
        const countdownEl = document.querySelector('.countdown');
        const getReadyEl = document.querySelector('.get-ready');
        let count = 3;

        // 显示"准备开始！"
        getReadyEl.classList.add('show');
        
        // 倒计时函数
        function updateCount() {
            if (count > 0) {
                countdownEl.textContent = count;
                countdownEl.classList.add('show');
                
                setTimeout(() => {
                    countdownEl.classList.remove('show');
                    setTimeout(() => {
                        count--;
                        updateCount();
                    }, 200);
                }, 800);
            } else {
                // 倒计时结束
                getReadyEl.classList.remove('show');
                countdownEl.classList.remove('show');
                
                // 开始游戏
                setTimeout(() => {
                    startGame();
                }, 500);
            }
        }

        // 开始倒计时
        updateCount();
    }

    // 修改学习界面显示函数
    function showStudySection() {
        // 显示学习界面和模式选择
        document.getElementById("studySection").style.display = "block";
        document.querySelector('.mode-select').style.display = "block";
        
        // 隐藏游戏相关元素
        document.getElementById("gameCanvas").style.display = "none";
        document.getElementsByClassName("score-container")[0].style.display = "none";
        
        // 显示当前需要学习的句子
        document.getElementById("studyText").textContent = sentences[currentSentenceIndex];
        document.getElementById("studyInstruction").textContent = "请先记忆上面的句子";
        
        // 重置游戏状态
        isGameStarted = false;
        if (gameInterval) {
            clearInterval(gameInterval);
        }
    }

    // 添加绘制眼睛的函数
    function drawEyes(segment, direction) {
        ctx.fillStyle = 'white';
        let eyeX1, eyeX2, eyeY1, eyeY2;
        
        // 根据方向调整眼睛位置
        switch(direction) {
            case 'RIGHT':
                eyeX1 = segment.x + snakeSize - 6;
                eyeX2 = eyeX1;
                eyeY1 = segment.y + 6;
                eyeY2 = segment.y + snakeSize - 6;
                break;
            case 'LEFT':
                eyeX1 = segment.x + 6;
                eyeX2 = eyeX1;
                eyeY1 = segment.y + 6;
                eyeY2 = segment.y + snakeSize - 6;
                break;
            case 'UP':
                eyeX1 = segment.x + 6;
                eyeX2 = segment.x + snakeSize - 6;
                eyeY1 = segment.y + 6;
                eyeY2 = eyeY1;
                break;
            case 'DOWN':
                eyeX1 = segment.x + 6;
                eyeX2 = segment.x + snakeSize - 6;
                eyeY1 = segment.y + snakeSize - 6;
                eyeY2 = eyeY1;
                break;
        }
        
        // 绘制眼睛
        ctx.beginPath();
        ctx.arc(eyeX1, eyeY1, 2, 0, Math.PI * 2);
        ctx.arc(eyeX2, eyeY2, 2, 0, Math.PI * 2);
        ctx.fillStyle = 'black';
        ctx.fill();
    }

    // 修改模式切换函数
    function switchMode() {
        isDoubleMode = !isDoubleMode;
        const modeBtn = document.querySelector('.mode-btn');
        if (isDoubleMode) {
            modeBtn.textContent = "切换为单人模式";
        } else {
            modeBtn.textContent = "切换为双人模式";
        }
    }

    // 修改处理玩家死亡函数
    function handlePlayerDeath(playerNum) {
        if (!isDoubleMode) {
            // 单人模式
            lives1--;
            updateScoreDisplay();
            
            if (lives1 <= 0) {
                lives1 = 3; // 重置生命值
                score = 0;  // 清零分数
                collectedTexts = []; // 清空收集的文字
                targetWordIndex = 0; // 重置目标索引
                correctWord = currentSentence[targetWordIndex];
                snake = [{ x: 100, y: 100 }]; // 重置蛇长度
                food = []; // 清空食物
                spawnFood(); // 重新生成食物
                endGame();
                return;
            }
            
            // 还有生命就继续游戏，保持当前食物和蛇长度
            showBottomHint(`还剩 ${lives1} 条命！`, () => {
                snake = [{ x: 100, y: 100 }].concat(snake.slice(1)); // 只重置蛇头位置，保持长度
                direction = "RIGHT";
            });
            return;
        }
        
        // 双人模式的处理
        if (playerNum === 1) {
            lives1--;
            updateScoreDisplay();
            
            if (lives1 <= 0) {
                lives1 = 3;
                score = 0;
                collectedTexts = [];
                targetWordIndex = 0;
                correctWord = currentSentence[targetWordIndex];
                snake = [{ x: 100, y: 100 }]; // 重置蛇1长度
            } else {
                // 还有生命，保持蛇长度
                snake = [{ x: 100, y: 100 }].concat(snake.slice(1));
            }
            
            player1Dead = true;
            showBottomHint(`玩家1还剩 ${lives1} 条命！正确句子：${sentences[currentSentenceIndex]}`, () => {
                player1Dead = false;
                direction = "RIGHT";
            });
        } else {
            lives2--;
            updateScoreDisplay();
            
            if (lives2 <= 0) {
                lives2 = 3;
                score2 = 0;
                collectedTexts2 = [];
                targetWordIndex2 = 0;
                correctWord2 = currentSentence[targetWordIndex2];
                snake2 = [{ x: canvas.width - 100, y: canvas.height - 100 }]; // 重置蛇2长度
            } else {
                // 还有生命，保持蛇长度
                snake2 = [{ x: canvas.width - 100, y: canvas.height - 100 }].concat(snake2.slice(1));
            }
            
            player2Dead = true;
            showBottomHint(`玩家2还剩 ${lives2} 条命！正确句子：${sentences[currentSentenceIndex]}`, () => {
                player2Dead = false;
                direction2 = "LEFT";
            });
        }

        // 如果两个玩家都没命了，清空食物并结束游戏
        if (lives1 <= 0 && lives2 <= 0) {
            food = []; // 只在两个玩家都没命时清空食物
            spawnFood();
            endGame();
        }
    }

    // 修改底部提示函数，添加回调功能
    function showBottomHint(text, callback) {
        const hintDiv = document.createElement('div');
        hintDiv.style.position = 'fixed';
        hintDiv.style.bottom = '20px';
        hintDiv.style.left = '0';
        hintDiv.style.width = '100%';
        hintDiv.style.textAlign = 'center';
        hintDiv.style.color = 'black';
        hintDiv.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
        hintDiv.style.padding = '10px';
        hintDiv.style.zIndex = '1000';
        hintDiv.style.fontSize = '18px';
        hintDiv.style.fontWeight = 'bold';
        hintDiv.style.boxShadow = '0 -2px 10px rgba(0,0,0,0.1)';
        hintDiv.textContent = text;
        document.body.appendChild(hintDiv);

        // 10秒后移除提示并执行回调
        setTimeout(() => {
            // 添加淡出动画
            hintDiv.style.transition = 'opacity 0.5s';
            hintDiv.style.opacity = '0';
            
            setTimeout(() => {
                document.body.removeChild(hintDiv);
                if (callback) callback();
            }, 500);
        }, 10000);
    }

    // 修改游戏结束动画显示
    function showGameOver() {
        const gameOverEmoji = document.getElementById("gameOverEmoji");
        if (gameOverEmoji) {
            gameOverEmoji.classList.add("show");
            setTimeout(() => {
                gameOverEmoji.classList.remove("show");
            }, 1500);
        }
    }

    // 修改重置游戏函数
    function resetGame() {
        // 重置生命值
        lives1 = 3;
        lives2 = 3;
        
        // 重置玩家状态
        player1Dead = false;
        player2Dead = false;
        
        // 重置分数
        score = 0;
        score2 = 0;
        
        // 重置收集的文字
        collectedTexts = [];
        collectedTexts2 = [];
        
        // 重置目标索引
        targetWordIndex = 0;
        targetWordIndex2 = 0;
        
        // 重置蛇的位置
        snake = [{ x: 100, y: 100 }];
        snake2 = [{ x: canvas.width - 100, y: canvas.height - 100 }];
        
        // 重置方向
        direction = "RIGHT";
        direction2 = "LEFT";
        
        // 清空食物
        food = [];
        
        // 更新分数显示
        updateScoreDisplay();
    }

    // 修改分数显示函数
    function updateScoreDisplay() {
        document.getElementById("score").textContent = `玩家1得分: ${score} (❤️: ${lives1})`;
        if (isDoubleMode) {
            document.getElementById("score2").textContent = `玩家2得分: ${score2} (❤️: ${lives2})`;
        }
    }

    // 添加句子卡相关函数
    function showSentenceCards() {
        const sentenceCards = document.querySelector('.sentence-cards');
        const sentenceList = document.getElementById('sentenceList');
        sentenceList.innerHTML = '';
        
        // 生成句子卡列表
        sentences.forEach((sentence, index) => {
            const card = document.createElement('div');
            card.className = 'sentence-card' + (index === currentSentenceIndex ? ' selected' : '');
            card.textContent = sentence;
            card.onclick = () => selectSentence(index);
            sentenceList.appendChild(card);
        });
        
        sentenceCards.style.display = 'block';
    }

    function selectSentence(index) {
        // 更新选中状态
        document.querySelectorAll('.sentence-card').forEach((card, i) => {
            card.classList.toggle('selected', i === index);
        });
        
        // 更新当前句子索引
        currentSentenceIndex = index;
        
        // 隐藏句子卡界面
        document.querySelector('.sentence-cards').style.display = 'none';
        
        // 重置游戏状态
        resetGame();
        
        // 显示学习界面
        showStudySection();
    }

    // 初始化
    window.onload = function() {
        // 初始化音频元素
        bgMusic = document.getElementById("bgMusic");
        if (bgMusic) {
            bgMusic.volume = 0.3; // 设置初始音量
            
            // 添加音频加载错误处理
            bgMusic.onerror = function() {
                console.error("背景音乐加载失败");
            };
        }

        // 初始化吃食物音效
        const eatSound = document.getElementById("eatSound");
        if (eatSound) {
            eatSound.volume = 0.5;
            eatSound.preload = 'auto';
            
            // 添加音频加载错误处理
            eatSound.onerror = function() {
                console.error("吃食物音效加载失败");
            };
        }

        // 初始化游戏结束音效
        const gameOverSound = document.getElementById("gameOverSound");
        if (gameOverSound) {
            gameOverSound.volume = 0.5;
            gameOverSound.preload = 'auto';
            
            // 添加音频加载错误处理
            gameOverSound.onerror = function() {
                console.error("游戏结束音效加载失败");
            };
        }

        // 为所有音频添加错误处理
        [bgMusic, eatSound, gameOverSound].forEach(audio => {
            if (audio) {
                audio.onerror = function() {
                    console.error(`音频 ${audio.id} 加载失败`);
                };
            }
        });

        // 初始化游戏状态
        isGameStarted = false;
        isDoubleMode = false;
        currentSentenceIndex = 0;
        
        // 显示学习界面
        showStudySection();
        
        // 确保游戏失败提示初始隐藏
        const emojiOverlay = document.getElementById("gameOverEmoji");
        if (emojiOverlay) {
            emojiOverlay.classList.remove("show");
        }
    }
</script>

</body>
</html>
